// pages/shouye/shouye.js
var deviceId;//连接的设备的ID
var i=0;
var serviceId=[];//各种服务的ID
var characteristicId=[];//
var shujubianhuan=[];
Page({
  data: {
          sendmsg:"",
          shujy:"31/.",
          long:"0",
          shumu:"",
          sousuo:"",
          status:"",
          zhuangtai:"未初始化",//
          shebei:"",//
          deviceName:"0",//
          deviceId:[],//
          devices:[],//
          connectedDeviceId:"",//已连接设备UUid
          services:"",//连接设备的服务
          characteristics:"",//连接设备的状态值
          writeServicweId:"",//可写服务UUid
          writeCharacteristicsId:"",//可写特征值UUid
          readServicweId:"",//可读服务UUid
          readCharacteristicsId:"",//可读特征值UUid
          notifyServicweId:"",//通知服务UUid
  },
shousuo:function(){
    var that=this;
    wx.openBluetoothAdapter({
      success:function(res){
        that.setData({
          zhuangtai:"适配成功，您已经成功开启蓝牙"
        })
        wx.getBluetoothAdapterState({
          success:function(res){
            that.setData({
              zhuangtai:"蓝牙适配器可用，当前蓝牙处于未连接状态"
            })
            that.zhoubian();
          },
          fail:function(res){
            that.setData({
              zhuangtai:"蓝牙适配器不可用，已经与蓝牙设备连接。"
            })
            wx.showModal({
              title: '注意',
              content: '您的蓝牙设备已经连接了其他的设备，请确保连接的是当前使用的设备',
            })
          }
        })
      },
      fail:function(res){
        that.setData({
          zhuangtai:"适配失败，请检查您的蓝牙设备是否开启"
        })
        wx.showModal({
          title: '注意',
          content: '您还未开启蓝牙，请先开启蓝牙',
        })
      }
    })

  },
  //开始搜索蓝牙设备
  zhoubian:function(){
      var that = this;
      setTimeout(() => {
      wx.startBluetoothDevicesDiscovery({
      success: function(res) {
        that.setData({
          zhuangtai:"正在搜索中。。。",
        })
      function ab2hex(buffer) {
       var hexArr = Array.prototype.map.call(
       new Uint8Array(buffer),
      function(bit) {
      return ('00' + bit.toString(16)).slice(-2)
       }
       )
      return hexArr.join('');
      }
      wx.getBluetoothDevices({  //获取周边蓝牙信息
         success: function (res) {
           that.setData({
            zhuangtai:"搜索设备:"+JSON.stringify(res.devices),
            shumu:"搜索到的蓝牙设备的数目："+res.devices.length,
            devices:res.devices
           })
          }
        })
    },
      fail(res) {
    }	
    })	
  }, 500)
  },
  //连接蓝牙设备
connectTO:function(e) {
  var that=this;
  setTimeout(() => {
	wx.createBLEConnection({
	deviceId: e.currentTarget.id,
	success: function(res) {
    that.setData({
      connectedDeviceId:e.currentTarget.id,
      zhuangtai: e.currentTarget.id,
       //zhuangtai:"已连接"+e.currentTarget.id+'==='+'连接设备返回：'+res.errMsg,
      msg1:"",
      shumu:"已经连接一个"
    })
    deviceId=e.currentTarget.id//连接的是哪一个保存在全局变量里面
    that.tingshisousuo();
},
  fail: function(res) {
    that.setData({
      zhuangtai:"连接失败",
    })
  }	,
  complete:function(){
    that.setData({
      // zhuangtai:"调用结束",
    })
  }
})
}, 1000)

},
//停止搜索周边设备
tingshisousuo:function(){
  var that=this;
  // setTimeout(() => {
  wx.stopBluetoothDevicesDiscovery({
    success: function(res)  {
      that.setData({
        zhuangtai:"停止搜索周边设备"+"/"+JSON.stringify(res.errMsg),
        suosou:res.discovering ? "；正在搜索":"；未在搜索",
        status:res.available ? "；可用" : "；不可用"
      })
      that.getservice();
    },
  })
// }, 500)
},
//获取蓝牙设备的 service 服务
getservice:function() {
  var that=this;
  // setTimeout(() => {
	wx.getBLEDeviceServices({
	deviceId: that.data.connectedDeviceId,
	success: function(res) {
for(var i=0;i<res.services.length;i++)
{
serviceId[i]=res.services[i].uuid;//将蓝牙模块的各种服务ID都保存在全局变量中
}
that.setData({
  services:res.services,//所有的服务ID
  zhuangtai:JSON.stringify(res.services),
})
 that.getBLEDeviceCharacteristics();
},
})	
// }, 500)
},
//获取蓝牙设备特征值:获取到的特征值有多个, 最后要用的事能读, 能写, 能监听的那个值的 uuid 作为特征值 id
getBLEDeviceCharacteristics:function() {
  var that=this;
  //var myuuid=that.data.services[0].uuid;//具有通知读写的属性的服务uuid
	wx.getBLEDeviceCharacteristics({
	deviceId: that.data.connectedDeviceId,//这里的deviceId需要在上面的getBLEDeviceServices或onBluetoothDeviceFound接口中获取
	serviceId: "0000ffe0-0000-1000-8000-00805f9b34fb",
	success: function(res) {
	for (var i = 0; i <res.characteristics.length; i++) {
    characteristicId[i]=res.characteristics[i].uuid;
    if(res.characteristics[i].properties.notify){
      that.setData({
        notifyServicweId:"0000ffe1-0000-1000-8000-00805f9b34fb",
        notifyCharacteristicsId:res.characteristics[i].uuid,
        })
    }
    if(res.characteristics[i].properties.write){
      that.setData({
        writeServicweId:"0000ffe1-0000-1000-8000-00805f9b34fb",
        writeCharacteristicsId:res.characteristics[i].uuid,
        })
    }
     if(res.characteristics[i].properties.read){
      that.setData({
        readServicweId:"0000ffe1-0000-1000-8000-00805f9b34fb",
        readCharacteristicsId:res.characteristics[i].uuid,
        })
    }
}	
that.setData({
  zhuangtai:JSON.stringify(res.characteristics)
})

that.uselanyachaaracteristic();
},
	fail: function(res) {
    that.setData({
      zhuangtai:"获取特征值失败"
    })
}	,
complete:function(){

  console.log("complete")
}
})	

},
//启用蓝牙特征值变化, // 启用低功耗蓝牙设备特征值变化时的 notify 功能
uselanyachaaracteristic:function(){
var that=this;
wx.notifyBLECharacteristicValueChange({
      state: true,//是否启用 notify
      deviceId: deviceId,//蓝牙ID
      serviceId: "0000ffe0-0000-1000-8000-00805f9b34fb",//蓝牙特征值对应服务的 uuid
      characteristicId:"0000ffe1-0000-1000-8000-00805f9b34fb",//蓝牙特征值的 uuid
      success:function(res) {
          /* 用来监听手机蓝牙设备的数据变化 */
        that.setData({
          zhuangtai:"启用状态值变化成功"
        })
        
      },
      fail:function(res) {
        that.setData({
          zhuangtai:"启用特征值变化失败"
        })
      }
  })
function ab2hex (buffer) {
  var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer), function (bit) {
          return ('00' + bit.toString(16)).slice(-2)
      }
  )
  return hexArr.join('')
}
wx.reLaunch({
  url: '../xiaoche/xiaoche'
})
wx.onBLECharacteristicValueChange(function(res){
  that.setData({
    zhuangtai:'接收的数据是：'+ab2hex(res.value)
  })
})
},
  // 断开设备连接
close() {
  var that=this
	if (that.data.connectedDeviceId) {
	wx.closeBLEConnection({
	deviceId: that.data.connectedDeviceId,
	success: function(res) {
	that.closeBluetoothAdapter()	
},
	fail(res) {
	
}	
})	
} else {
	that.closeBluetoothAdapter()	
}	
},
// 关闭蓝牙模块
closeBluetoothAdapter:function() {
  var that=this
	wx.closeBluetoothAdapter({
	success: function(res) {
	that.setData({
    zhuangtai:"断开蓝牙成功"
  })
},
	fail: function(err) {
}	
})	
},
getmsg: function (event){
    for (var i = 0; i < event.detail.length; i++) {
      shujubianhuan[i]=event.detail.value[i]-(-48);
    }
  this.setData({
    sendmsg:event.detail.value-(-48)+'4746'
  })
},
sendData:function(event){
  var that = this
  var hex = that.data.sendmsg  //要发送的信息
  var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
    return parseInt(h,0)
  }))
   var buffer1 = typedArray.buffer
  wx.writeBLECharacteristicValue({
    deviceId: that.data.connectedDeviceId,
    serviceId: "0000ffe0-0000-1000-8000-00805f9b34fb",
    characteristicId: "0000ffe1-0000-1000-8000-00805f9b34fb",
    value: buffer1,
    // 这里的value是ArrayBuffer类型
    success: function (res) {
      that.setData({
        zhuangtai:"发送数据成功"
      })
    },
    fail(res){
      that.setData({
        zhuangtai:"发送数据失败"
      })
    }
  })
},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})




